package com.quanshu.exchange.support.chat;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.utils.CheckUtil;

import java.util.List;

public class ChatCommonUtils {
    private static final String TAG = "CommonUtils";

    /**
     * check if network avalable
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }

        return false;
    }

    /**
     * check if sdcard exist
     *
     * @return
     */
    public static boolean isSdcardExist() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    public static EMMessage createExpressionMessage(String toChatUsername, String expressioName, String identityCode) {
        EMMessage message = EMMessage.createTxtSendMessage("[" + expressioName + "]", toChatUsername);
        if (identityCode != null) {
            message.setAttribute(ChatConstant.MESSAGE_ATTR_EXPRESSION_ID, identityCode);
        }
        message.setAttribute(ChatConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, true);
        return message;
    }

    /**
     * Get digest according message type and content
     *
     * @param message
     * @param context
     * @return
     */
    public static String getMessageDigest(EMMessage message, Context context) {
        String digest = "";
        switch (message.getType()) {
            case LOCATION:
                if (message.direct() == EMMessage.Direct.RECEIVE) {
                    digest = getString(context, R.string.location_recv);
                    digest = String.format(digest, message.getFrom());
                    return digest;
                } else {
                    digest = getString(context, R.string.location_prefix);
                }
                break;
            case IMAGE:
                digest = getString(context, R.string.picture);
                break;
            case VOICE:
                digest = getString(context, R.string.voice_prefix);
                break;
            case VIDEO:
                digest = getString(context, R.string.video);
                break;
            case TXT:
                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                String callType;
                try {
                    callType = message.getStringAttribute(ChatConstant.Chat_ext_attr_call_type);
                    if (callType != null) {
                        if (callType.equals("Video")) {
                            digest = getString(context, R.string.video_call);
                        } else if (callType.equals("Voice")) {
                            digest = getString(context, R.string.voice_call);
                        }
                        break;
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                String redPackageID;
                try {
                    redPackageID = message.getStringAttribute(ChatConstant.Chat_ext_attr_red_package_id);
                    if (redPackageID != null) {
                        digest = getString(context, R.string.red_package);
                        break;
                    } else {
                        digest = txtBody.getMessage();
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    digest = txtBody.getMessage();
                }
                break;
            case FILE:
                digest = getString(context, R.string.file);
                break;
            default:
                return "";
        }

        return digest;
    }

    static String getString(Context context, int resId) {
        return context.getResources().getString(resId);
    }

    /**
     * get top activity
     *
     * @param context
     * @return
     */
    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null)
            return runningTaskInfos.get(0).topActivity.getClassName();
        else
            return "";
    }


    /**
     * change the chat type to EMConversationType
     *
     * @param chatType
     * @return
     */
    public static EMConversationType getConversationType(int chatType) {
        if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
            return EMConversationType.Chat;
        } else if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
            return EMConversationType.GroupChat;
        } else {
            return EMConversationType.ChatRoom;
        }
    }

    /**
     * \~chinese
     * 判断是否是免打扰的消息,如果是app中应该不要给用户提示新消息
     *
     * @param message return
     *                <p>
     *                \~english
     *                check if the message is kind of slient message, if that's it, app should not play tone or vibrate
     * @param message
     * @return
     */
    public static boolean isSilentMessage(EMMessage message) {
        return message.getBooleanAttribute("em_ignore_notification", false);
    }


    /**
     * 获取消息类型
     *
     * @param message
     * @return
     */
    public static int getChatMessageType(EMMessage message) {
        if (message.getFrom() != null && message.getFrom().equals("admin")) {
            return ChatConstant.MESSAGE_TYPE_NOTIFY;
        }
        int messageType = ChatConstant.MESSAGE_TYPE_TXT;
        switch (message.getType()) {
            case IMAGE:
                messageType = ChatConstant.MESSAGE_TYPE_IMAGE;
                break;
            case VOICE:
                messageType = ChatConstant.MESSAGE_TYPE_VOICE;
                break;
            case VIDEO:
                messageType = ChatConstant.MESSAGE_TYPE_VIDEO;
                break;
            case TXT:
                String callType;
                try {
                    callType = message.getStringAttribute(ChatConstant.Chat_ext_attr_call_type);
                    if (callType != null) {
                        if (callType.equals("Video")) {
                            messageType = ChatConstant.MESSAGE_TYPE_VIDEO_CALL;
                        } else if (callType.equals("Voice")) {
                            messageType = ChatConstant.MESSAGE_TYPE_VOICE_CALL;
                        }
                        break;
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                String redPackageID;
                try {
                    redPackageID = message.getStringAttribute(ChatConstant.Chat_ext_attr_red_package_id);
                    if (redPackageID != null) {
                        messageType = ChatConstant.MESSAGE_TYPE_RED_PACKAGE;
                        break;
                    } else {
                        messageType = ChatConstant.MESSAGE_TYPE_TXT;
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    messageType = ChatConstant.MESSAGE_TYPE_TXT;
                }
                break;
            default:
                messageType = ChatConstant.MESSAGE_TYPE_TXT;
        }
        return messageType;
    }


    /**
     * @param message
     * @param groupOwner
     * @param currentUserId
     * @return true: visible  ,false: invisible
     */
    public static boolean getChatMsgVisibility(EMMessage message, String groupOwner, String currentUserId) {
        if (message == null) {
            return false;
        }
        // 如果是发送的消息
        if (message.direct() == EMMessage.Direct.SEND) {
            return true;
        } else {
            // 如果是私聊消息
            if (message.getChatType() == EMMessage.ChatType.Chat) {
                return true;
            }
            // 如果是 admin 消息
            if (message.getFrom().equals("admin")) {
                return true;
            }
            // 如果当前用户是群主
            if (currentUserId.equals(groupOwner)) {
                return true;
            }

            String reply = null;
            String redPackageId = null;

            // 判断是不是公开信息
            boolean isToAll = message.getBooleanAttribute(ChatConstant.Chat_ext_attr_is_toAll, false);
            if (isToAll) {
                return true;
            }

            try {
                reply = message.getStringAttribute(ChatConstant.Chat_reply_member);
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            try {
                redPackageId = message.getStringAttribute(ChatConstant.Chat_ext_attr_red_package_id);
            } catch (HyphenateException e) {
                e.printStackTrace();
            }

            // 回复不是空
            if (reply != null && reply.length() > 0) {
                // 回复是我
                if (reply.equals(currentUserId)) {
                    return true;
                }
                // 回复不是我
                else {
                    return false;
                }
            }

            // 如果是红包信息
            if (redPackageId != null && redPackageId.length() > 0) {
                return true;
            } else {
                // 如果是群主消息
                if (CheckUtil.isValidate(groupOwner) && message.getFrom().equals(groupOwner)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

}